<template>
  <div class="chart-container">
    <div class="chart-header" v-if="title">
      <div class="chart-title">{{ title }}</div>
    </div>
    <div ref="chartRef" class="chart"></div>
    <!-- 自定义图例 -->
    <div class="custom-legend" v-if="chartType === 'pie'">
      <div class="legend-item" v-for="(item, index) in ['茶民宿', '茶博物馆', '茶馆', '茶味活动', '景点文化']" :key="index">
        <span class="legend-color" :style="{ backgroundColor: ['#5470C6', '#91CC75', '#FAC858', '#EE6666', '#73C0DE'][index] }"></span>
        <span class="legend-text">{{ item }}</span>
      </div>
    </div>
  </div>
</template>

<script setup>
import { onMounted, ref, onBeforeUnmount } from 'vue';
import * as echarts from 'echarts';

const props = defineProps({
  title: {
    type: String,
    default: ''
  },
  chartType: {
    type: String,
    default: 'line' // 'line', 'bar', 'pie'
  },
  selectedDate: {  // 新增属性，接收选定日期
    type: Date,
    default: () => new Date()
  }
});

const chartRef = ref(null);
const chartInstance = ref(null);

onMounted(() => {
  if (chartRef.value) {
    // 确保容器有正确的尺寸
    const container = chartRef.value;
    if (container.offsetHeight === 0) {
      container.style.height = '450px';
    }
    
    // 初始化图表
    chartInstance.value = echarts.init(container);
    
    // 根据类型渲染对应的图表
    if (props.chartType === 'line') {
      renderLineChart();
    } else if (props.chartType === 'bar') {
      renderBarChart();
    } else if (props.chartType === 'pie') {
      renderPieChart();
    }
    
    // 监听窗口大小变化
    const handleResize = () => {
      if (chartInstance.value) {
        chartInstance.value.resize();
      }
    };
    
    window.addEventListener('resize', handleResize);
    
    // 组件卸载时清理
    onBeforeUnmount(() => {
      window.removeEventListener('resize', handleResize);
      if (chartInstance.value) {
        chartInstance.value.dispose();
        chartInstance.value = null;
      }
    });
  }
});

const renderLineChart = () => {
  if (!chartRef.value) return

  const months = ['1月', '2月', '3月', '4月', '5月', '6月', '7月', '8月', '9月', '10月', '11月', '12月']
  const lowRisk = [20, 18, 15, 23, 25, 33, 28, 25, 27, 22, 18, 16]
  const mediumRisk = [15, 12, 10, 18, 20, 25, 22, 18, 16, 14, 12, 10]
  const highRisk = [5, 4, 6, 8, 12, 18, 15, 10, 8, 6, 5, 4]
  const pestTrend = [30, 28, 26, 42, 50, 65, 58, 46, 44, 35, 30, 25]

  chartInstance.value.setOption({
    tooltip: {
      trigger: 'axis',
      axisPointer: {
        type: 'shadow'
      }
    },
    legend: {
      data: ['低危险', '中危险', '高危险', '虫害趋势'],
      top: '4%',
      itemGap: 12
    },
    grid: {
      left: '30px',
      right: '55px',
      bottom: '6%',
      top: '22%',
      containLabel: true
    },
    xAxis: {
      type: 'category',
      data: months,
      axisLabel: {
        rotate: 0,
        interval: 0,
        fontSize: 13,
        show: true,
        hideOverlap: false,
        padding: [0, 0, 15, 0]
      }
    },
    yAxis: [
      {
        type: 'value',
        name: '风险分布',
        min: 0,
        max: 80,
        interval: 20,
        position: 'left',
        axisLabel: {
          formatter: '{value}',
          margin: 8,
          fontSize: 13
        },
        nameTextStyle: {
          padding: [0, 0, 0, -5]
        }
      },
      {
        type: 'value',
        name: '虫害指数',
        min: 0,
        max: 70,
        interval: 10,
        position: 'right',
        offset: 0,
        axisLabel: {
          formatter: function(value) {
            // 使用更精确的对齐方式
            let numStr = value.toString();
            // 个位数前面加一个空格
            if (value < 10) {
              numStr = ' ' + numStr;
            }
            return numStr;
          },
          margin: 8,
          fontSize: 13
        },
        nameTextStyle: {
          padding: [0, -5, 0, 0]
        }
      }
    ],
    series: [
      {
        name: '低危险',
        type: 'bar',
        stack: '风险分布',
        data: lowRisk,
        barCategoryGap: '5%', // 添加类目间距调整
      },
      {
        name: '中危险',
        type: 'bar',
        stack: '风险分布',
        data: mediumRisk
      },
      {
        name: '高危险',
        type: 'bar',
        stack: '风险分布',
        data: highRisk
      },
      {
        name: '虫害趋势',
        type: 'line',
        yAxisIndex: 1,
        smooth: true,
        lineStyle: {
          width: 4
        },
        symbolSize: 8,
        data: pestTrend
      }
    ]
  });
  
  // 清除之前的事件监听
  chartInstance.value.off('mousemove');
  chartInstance.value.off('mouseout');
  
  // 由于现在使用内置的axisPointer功能，不再需要自定义的辅助线逻辑
  // 但我们保留mouseout事件处理，以确保离开图表时清除任何可能的标记
  chartInstance.value.on('mouseout', () => {
    chartInstance.value.setOption({
      series: [{
        markLine: {
          data: []
        }
      }]
    }, false);
  });
};

const renderBarChart = () => {           //气象情况
  // 获取选定日期及其后6天的日期
  const days = [];
  const startDate = props.selectedDate || new Date();
  
  for (let i = 0; i < 7; i++) {
    const date = new Date(startDate);
    date.setDate(startDate.getDate() + i);
    const month = date.getMonth() + 1;
    const day = date.getDate();
    days.push(`${month}/${day}`);
  }
  
  // 根据选定日期生成对应的气象数据
  // 这里使用一个简单的算法基于日期生成数据，实际应用可能需要从API获取真实数据
  const temperature = [];
  const rainfall = [];
  const humidity = [];
  
  for (let i = 0; i < 7; i++) {
    const date = new Date(startDate);
    date.setDate(startDate.getDate() + i);
    const dayOfMonth = date.getDate();
    const monthOfYear = date.getMonth() + 1;
    
    // 生成基于日期的伪随机温度 (20-28°C)
    const tempBase = 20 + ((dayOfMonth * monthOfYear) % 9);
    temperature.push(tempBase);
    
    // 生成基于日期的伪随机降水量 (0-45mm)
    const rainBase = ((dayOfMonth + monthOfYear) % 5 === 0) ? 35 + (dayOfMonth % 11) : (dayOfMonth % 3 === 0 ? 10 + (dayOfMonth % 11) : 0);
    rainfall.push(rainBase);
    
    // 生成基于日期的伪随机湿度 (60-85%)
    const humidityBase = 60 + ((dayOfMonth + monthOfYear * 2) % 26);
    humidity.push(humidityBase);
  }
  
  const option = {
    tooltip: {
      trigger: 'axis',
      backgroundColor: 'rgba(255, 255, 255, 0.9)',
      borderColor: '#eee',
      borderWidth: 1,
      textStyle: {
        color: '#333'
      },
      formatter: function(params) {
        let res = params[0].name + '<br/>';
        params.forEach(item => {
          let value = item.value;
          let unit = '';
          if (item.seriesName.includes('温度')) unit = '°C';
          if (item.seriesName.includes('降水量')) unit = 'mm';
          if (item.seriesName.includes('湿度')) unit = '%';
          
          res += `<div style="display:flex;align-items:center;margin:5px 0;">
                   <span style="display:inline-block;width:10px;height:10px;background:${item.color};margin-right:5px;"></span>
                   <span style="margin-right:5px;">${item.seriesName}:</span>
                   <span style="font-weight:bold;">${value}${unit}</span>
                 </div>`;
        });
        return res;
      },
      axisPointer: {
        type: 'cross',
        crossStyle: {
          color: 'rgba(200, 225, 255, 0.6)'
        }
      }
    },
    legend: {
      data: ['温度(°C)', '降水量(mm)', '湿度(%)'],
      top: 6,
      itemGap: 15
    },
    grid: {
      top: '15%',
      right: '10%',
      bottom: '15%',
      left: '10%',
      containLabel: true,
      height: '75%'
    },
    xAxis: {
      type: 'category',
      data: days,
      axisLine: {
        lineStyle: {
          color: '#999'
        }
      },
      axisTick: {
        show: false
      },
      axisLabel: {
        interval: 0,
        fontSize: 11,
        show: true,
        hideOverlap: false,
        padding: [5, 0, 5, 0]
      }
    },
    yAxis: [
      {
        type: 'value',
        name: '温度/湿度',
        min: 0,
        max: 100,
        interval: 20,
        position: 'left',
        axisLine: {
          show: false
        },
        axisTick: {
          show: false
        },
        splitLine: {
          lineStyle: {
            color: '#eee'
          }
        },
        axisLabel: {
          formatter: '{value}',
          margin: 8,
          fontSize: 11
        },
        nameTextStyle: {
          padding: [0, 0, 0, -5],
          fontSize: 11
        }
      },
      {
        type: 'value',
        name: '降水量',
        min: 0,
        max: 50,
        interval: 10,
        position: 'right',
        offset: 0,
        axisLine: {
          show: false
        },
        axisTick: {
          show: false
        },
        splitLine: {
          show: false
        },
        axisLabel: {
          formatter: '{value} mm',
          margin: 8,
          fontSize: 11
        },
        nameTextStyle: {
          padding: [0, -5, 0, 0],
          fontSize: 11
        }
      }
    ],
    series: [
      {
        name: '温度(°C)',
        type: 'line',
        smooth: true,
        data: temperature,
        symbolSize: 5,
        lineStyle: {
          width: 1.5
        },
        itemStyle: {
          color: '#FF9F45'
        }
      },
      {
        name: '降水量(mm)',
        type: 'bar',
        yAxisIndex: 1,
        data: rainfall,
        barWidth: '40%',
        barCategoryGap: '4%',
        itemStyle: {
          color: '#5470C6'
        }
      },
      {
        name: '湿度(%)',
        type: 'line',
        smooth: true,
        data: humidity,
        symbolSize: 5,
        lineStyle: {
          width: 1.5
        },
        itemStyle: {
          color: '#91CC75'
        }
      }
    ]
  };
  
  // 创建图表
  chartInstance.value.setOption(option);
  
  // 确保图表尺寸正确
  setTimeout(() => {
    chartInstance.value.resize();
  }, 50);
};

// 添加饼图渲染方法
const renderPieChart = () => {
  const teaManagementData = [
    { value: 27, name: '茶民宿' },
    { value: 18, name: '茶博物馆' },
    { value: 15, name: '茶馆' },
    { value: 18, name: '茶味活动' },
    { value: 22, name: '景点文化' }
  ];
  
  const option = {
    tooltip: {
      trigger: 'item',
      formatter: '{a} <br/>{b}: {c} ({d}%)'
    },
    legend: {
      orient: 'horizontal',
      bottom: 40,
      left: 'center',
      itemWidth: 20,
      itemHeight: 14,
      itemGap: 20,
      textStyle: {
        fontSize: 14,
        color: '#333'
      },
      data: teaManagementData.map(item => item.name)
    },
    series: [
      {
        name: '茶文化分布',
        type: 'pie',
        radius: ['25%', '70%'],
        center: ['50%', '35%'],
        avoidLabelOverlap: true,
        itemStyle: {
          borderRadius: 10,
          borderColor: '#fff',
          borderWidth: 8
        },
        label: {
          show: true,
          position: 'outside',
          formatter: '{d}%',
          fontSize: 12
        },
        labelLine: {
          show: true,
          length: 15,
          length2: 10
        },
        emphasis: {
          label: {
            show: true,
            fontSize: 14,
            fontWeight: 'bold'
          }
        },
        data: teaManagementData
      }
    ],
    color: ['#5470C6', '#91CC75', '#FAC858', '#EE6666', '#73C0DE']
  };
  
  // 确保图表实例存在
  if (chartInstance.value) {
    chartInstance.value.clear();
    chartInstance.value.setOption(option);
  }
};

// 添加对外暴露的方法，用于接收日期更新
defineExpose({
  updateWeatherData: (date) => {
    props.selectedDate = date || new Date();
    renderBarChart();
  }
});
</script>

<style scoped>
.chart-container {
  height: 100%;
  display: flex;
  flex-direction: column;
  position: relative;
}

.chart-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 15px;
}

.chart-title {
  font-size: 16px;
  font-weight: 600;
  color: #333;
}

.chart {
  flex: 1;
  min-height: 270px;
  width: 100%;
  margin-right: -15px;
}

/* 自定义图例样式 */
.custom-legend {
  display: none;
}
</style> 